#! /bin/bash

cd /path/to/working/directory

/Applications/plink_mac_20240818/plink --vcf M4.vcf --make-bed --out M4 --allow-extra-chr
awk '{$1="0";print $0}' M4.bim > M4.bim.tmp
mv M4.bim.tmp M4.bim


for i in {1..3}
do
/Applications/admixture_macosx-1.3.0/admixture -j8 --cv=10 M4.bed $i > log${i}.out
done

grep "CV" *out | awk '{print $3,$4}' | sed -e 's/(//;s/)//;s/://;s/K=//'  > Limno.cv.error

awk '{split($1,name,"."); print $1,name[2]}' M4.nosex > Limno.list

R
setwd("/path/to/working/directory/")
df <- read.table("Limno.cv.error", sep = " ")
plot(df)

tbl=read.table("M4.3.Q")
barplot(t(as.matrix(tbl)), col=rainbow(3),
xlab="Individual #", ylab="Ancestry", border=NA)

svglite("admixture_stacked_bar.svg", width = 80, height = 20)
tbl=read.table("M4.3.Q")
barplot(t(as.matrix(tbl)), col=rainbow(3),
xlab="Individual #", ylab="Ancestry", border=NA)
dev.off()

svglite("k.svg", width = 80, height = 20)
plot(df)
dev.off()
